import React, { useState, useEffect } from 'react';
import { 
  Tabs, 
  Card, 
  List, 
  Badge, 
  Space, 
  Toast, 
  Button, 
  Radio, 
  Popup, 
  Dialog, 
  Rate, 
  TextArea, 
  Form, 
  Input, 
  Stepper,
  NavBar,
  InfiniteScroll 
} from 'antd-mobile';
import { UnorderedListOutline, PayCircleOutline, TruckOutline, MessageOutline, AddOutline, LeftOutline } from 'antd-mobile-icons';
import { useLocation, useNavigate } from 'react-router-dom';
import styles from './Operation.module.css';

// Enhanced mock data with more items
const MOCK_ORDER_DATA = {
  unpaid: [
    { 
      id: '1001', 
      title: '特级茅台酒', 
      price: 1999, 
      time: new Date().toISOString(), 
      status: '待付款', 
      paymentTime: 1800000,
      image: 'https://img.alicdn.com/bao/uploaded/i1/2206499166101/O1CN01WDfLPH1wM7pLhQ7pZ_!!0-item_pic.jpg'
    }, 
    { 
      id: '1002', 
      title: '手工艺品', 
      price: 299, 
      time: new Date(Date.now() - 86400000).toISOString(), 
      status: '待付款', 
      paymentTime: 600000,
      image: 'https://img.alicdn.com/bao/uploaded/i4/2201504841617/O1CN01m4XZQe1xZExXeQmzO_!!0-item_pic.jpg'
    }
  ],
  unsent: [
    { 
      id: '1003', 
      title: 'iPhone 15 Pro Max', 
      price: 9999, 
      time: new Date(Date.now() - 2 * 86400000).toISOString(), 
      status: '待发货',
      image: 'https://img.alicdn.com/bao/uploaded/i1/2616970884/O1CN01IOuDk21IOudjKvXZg_!!0-item_pic.jpg',
      address: {
        receiver: '张三',
        phone: '13800138000',
        address: '北京市朝阳区建国路88号'
      }
    },
    { 
      id: '1008', 
      title: '无线耳机', 
      price: 499, 
      time: new Date(Date.now() - 1 * 86400000).toISOString(), 
      status: '待发货',
      image: 'https://img.alicdn.com/bao/uploaded/i4/2201504841617/O1CN01m4XZQe1xZExXeQmzO_!!0-item_pic.jpg',
      address: {
        receiver: '李四',
        phone: '13900139000',
        address: '上海市浦东新区张江高科技园区'
      }
    }
  ],
  unreceived: [
    { 
      id: '1004', 
      title: 'MacBook Pro', 
      price: 15999, 
      time: new Date(Date.now() - 3 * 86400000).toISOString(), 
      status: '已发货',
      logistics: {
        carrier: '顺丰速运',
        trackingNumber: 'SF123456789',
        status: '运输中',
        info: [
          { time: '2023-10-01 10:00', content: '已发货', location: '深圳' },
          { time: '2023-10-02 15:30', content: '运输中', location: '广州转运中心' }
        ]
      },
      image: 'https://img.alicdn.com/bao/uploaded/i1/2206499166101/O1CN01WDfLPH1wM7pLhQ7pZ_!!0-item_pic.jpg'
    },
    { 
      id: '1009', 
      title: '高档手表', 
      price: 3999, 
      time: new Date(Date.now() - 2 * 86400000).toISOString(), 
      status: '已发货',
      logistics: {
        carrier: '中通快递',
        trackingNumber: 'ZT987654321',
        status: '运输中',
        info: [
          { time: '2023-10-03 09:00', content: '已发货', location: '杭州' },
          { time: '2023-10-04 14:20', content: '运输中', location: '上海转运中心' }
        ]
      },
      image: 'https://img.alicdn.com/bao/uploaded/i1/2616970884/O1CN01IOuDk21IOudjKvXZg_!!0-item_pic.jpg'
    }
  ],
  uncommented: [
    { 
      id: '1006', 
      title: 'iPad Air', 
      price: 4999, 
      time: new Date(Date.now() - 5 * 86400000).toISOString(), 
      status: '已收货',
      image: 'https://img.alicdn.com/bao/uploaded/i1/2616970884/O1CN01IOuDk21IOudjKvXZg_!!0-item_pic.jpg'
    },
    { 
      id: '1010', 
      title: '红酒礼盒', 
      price: 799, 
      time: new Date(Date.now() - 4 * 86400000).toISOString(), 
      status: '已收货',
      image: 'https://img.alicdn.com/bao/uploaded/i4/2201504841617/O1CN01m4XZQe1xZExXeQmzO_!!0-item_pic.jpg'
    }
  ],
  afterSales: [
    { 
      id: '1007', 
      title: '运动鞋', 
      price: 599, 
      time: new Date(Date.now() - 7 * 86400000).toISOString(), 
      status: '退款中',
      refundReason: '尺码不合适',
      refundStatus: '处理中',
      refundProgress: [
        { time: '2023-09-28 14:30', status: '退款申请已提交' },
        { time: '2023-09-29 09:15', status: '商家处理中' }
      ],
      image: 'https://img.alicdn.com/bao/uploaded/i4/2201504841617/O1CN01m4XZQe1xZExXeQmzO_!!0-item_pic.jpg'
    },
    { 
      id: '1011', 
      title: '黑椒牛排饭', 
      price: 28.5, 
      time: new Date(Date.now() - 1 * 86400000).toISOString(), 
      status: '退款完成',
      refundReason: '送餐超时',
      refundStatus: '已完成',
      refundProgress: [
        { time: '2023-10-09 12:30', status: '退款申请已提交' },
        { time: '2023-10-09 13:15', status: '商家已同意' },
        { time: '2023-10-09 15:30', status: '退款已完成' }
      ],
      image: 'https://img.alicdn.com/bao/uploaded/i1/2206499166101/O1CN01WDfLPH1wM7pLhQ7pZ_!!0-item_pic.jpg'
    }
  ]
};

// 生成更多订单数据用于无限滚动
const generateMoreOrders = (count) => {
  const result = [];
  for (let i = 0; i < count; i++) {
    const randomType = Math.floor(Math.random() * 5);
    const baseId = 2000 + i;
    const basePrice = Math.floor(Math.random() * 1000) + 100;
    const baseTime = Date.now() - Math.floor(Math.random() * 30) * 86400000;
    
    const order = {
      id: `${baseId}`,
      title: `商品${baseId}`,
      price: basePrice,
      time: new Date(baseTime).toISOString(),
      image: 'https://img.alicdn.com/bao/uploaded/i1/2206499166101/O1CN01WDfLPH1wM7pLhQ7pZ_!!0-item_pic.jpg'
    };
    
    switch (randomType) {
      case 0:
        order.status = '待付款';
        order.paymentTime = 1800000;
        break;
      case 1:
        order.status = '待发货';
        order.address = {
          receiver: '王五',
          phone: '13700137000',
          address: '广州市天河区珠江新城'
        };
        break;
      case 2:
        order.status = '已发货';
        order.logistics = {
          carrier: '圆通速递',
          trackingNumber: `YT${baseId}${baseId}`,
          status: '运输中',
          info: [
            { time: new Date(baseTime + 86400000).toISOString(), content: '已发货', location: '上海' },
            { time: new Date(baseTime + 2 * 86400000).toISOString(), content: '运输中', location: '杭州转运中心' }
          ]
        };
        break;
      case 3:
        order.status = '已收货';
        break;
      case 4:
        order.status = '退款中';
        order.refundReason = ['商品质量问题', '发错货', '不喜欢'][Math.floor(Math.random() * 3)];
        order.refundStatus = ['处理中', '已完成'][Math.floor(Math.random() * 2)];
        break;
    }
    
    result.push(order);
  }
  return result;
};

const Operation = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const orderType = location.state?.orderType || 'all';

  const [activeKey, setActiveKey] = useState(orderType);
  const [orderData, setOrderData] = useState({
    all: [],
    unpaid: [],
    unsent: [],
    unreceived: [],
    uncommented: [],
    afterSales: []
  });
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [allOrdersPage, setAllOrdersPage] = useState(1);

  // Initialize with mock data
  const initializeMockData = () => {
    setLoading(true);
    const data = MOCK_ORDER_DATA;
    const allOrders = [
      ...data.unpaid,
      ...data.unsent,
      ...data.unreceived,
      ...data.uncommented,
      ...data.afterSales
    ];
    
    setOrderData({
      all: allOrders,
      unpaid: data.unpaid,
      unsent: data.unsent,
      unreceived: data.unreceived,
      uncommented: data.uncommented,
      afterSales: data.afterSales
    });
    setLoading(false);
  };

  // Load more data for infinite scroll
  const loadMore = async () => {
    if (activeKey !== 'all') return;
    
    setLoading(true);
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const newOrders = generateMoreOrders(5);
      
      setOrderData(prev => ({
        ...prev,
        all: [...prev.all, ...newOrders]
      }));
      
      // Simulate no more data after 5 pages
      if (allOrdersPage >= 5) {
        setHasMore(false);
      } else {
        setAllOrdersPage(prev => prev + 1);
      }
    } catch (error) {
      Toast.show({
        content: '加载失败',
        position: 'center'
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    initializeMockData();
  }, []);

  useEffect(() => {
    if (location.state?.orderType) {
      setActiveKey(location.state.orderType);
    }
  }, [location.state?.orderType]);

  const handleTabChange = (key) => {
    setActiveKey(key);
    if (key === 'all') {
      setHasMore(true);
      setAllOrdersPage(1);
    }
  };

  const tabs = [
    { key: 'all', title: '全部订单', content: orderData.all },
    { key: 'unpaid', title: '待付款', content: orderData.unpaid },
    { key: 'unsent', title: '待发货', content: orderData.unsent },
    { key: 'unreceived', title: '待收货', content: orderData.unreceived },
    { key: 'uncommented', title: '待评论', content: orderData.uncommented },
    { key: 'afterSales', title: '退款/售后', content: orderData.afterSales }
  ];

  return (
    <div className={styles['operation-container']}>
      <NavBar 
    
        onBack={() => navigate(-1)}
        style={{ '--height': '48px' }}
      >
        我的订单
      </NavBar>
      
      <Tabs
        activeKey={activeKey}
        onChange={handleTabChange}
        style={{ '--title-font-size': '14px', '--adm-color-primary': '#ff4d4f' }}
      >
        {tabs.map(item => (
          <Tabs.Tab title={item.title} key={item.key}>
            {loading && item.content.length === 0 ? (
              <div className={styles['loading-state']}>
                <div>加载中...</div>
              </div>
            ) : (
              <OrderList 
                data={item.content} 
                status={item.key} 
                refreshData={initializeMockData}
                hasMore={item.key === 'all' ? hasMore : false}
                loadMore={item.key === 'all' ? loadMore : null}
              />
            )}
          </Tabs.Tab>
        ))}
      </Tabs>
    </div>
  );
};

const OrderList = ({ data, status, refreshData, hasMore, loadMore }) => {
  const [showPopup, setShowPopup] = useState(false);
  const [cancelReason, setCancelReason] = useState(null);
  const [currentOrderId, setCurrentOrderId] = useState(null);
  const [showReviewPopup, setShowReviewPopup] = useState(false);
  const [rating, setRating] = useState(5);
  const [comment, setComment] = useState('');
  const [reviewingOrderId, setReviewingOrderId] = useState(null);
  const [showRefundPopup, setShowRefundPopup] = useState(false);
  const [refundReason, setRefundReason] = useState('商品质量问题');
  const [refundDescription, setRefundDescription] = useState('');
  const [refundingOrderId, setRefundingOrderId] = useState(null);
  const [showAddressPopup, setShowAddressPopup] = useState(false);
  const [addressForm, setAddressForm] = useState({
    receiver: '',
    phone: '',
    address: ''
  });
  const [modifyingOrderId, setModifyingOrderId] = useState(null);

  if (data.length === 0) {
    return <div className={styles['empty-state']}>暂无{status === 'all' ? '' : status}订单</div>;
  }

  const handleCancelOrderClick = (orderId) => {
    setCurrentOrderId(orderId);
    setShowPopup(true);
  };

  const handlePaymentClick = async (orderId) => {
    await handlePayment(orderId, refreshData);
  };

  const handleCancelOrderConfirm = async (orderId, reason) => {
    await handleCancelOrder(orderId, reason, refreshData);
    setShowPopup(false);
  };

  const handleConfirmReceiptClick = async (orderId) => {
    await handleConfirmReceipt(orderId, refreshData);
  };

  const handleApplyRefundClick = async (orderId) => {
    setRefundingOrderId(orderId);
    setShowRefundPopup(true);
  };

  const handleReviewClick = async (orderId) => {
    setReviewingOrderId(orderId);
    setShowReviewPopup(true);
  };

  const handleUrgeShipmentClick = async (orderId) => {
    await handleUrgeShipment(orderId);
  };

  const handleOrderAgainClick = async (orderId) => {
    await handleOrderAgain(orderId);
  };

  const handleAfterSaleClick = async (orderId) => {
    await handleAfterSale(orderId);
  };

  const handleContactServiceClick = async (orderId) => {
    await handleContactService(orderId);
  };

  const handleViewRefundDetailClick = async (orderId) => {
    await handleViewRefundDetail(orderId);
  };

  const handleViewLogisticsClick = async (orderId) => {
    await handleViewLogistics(orderId);
  };

  const handleModifyAddressClick = async (orderId) => {
    const order = data.find(item => item.id === orderId);
    if (order && order.address) {
      setAddressForm({
        receiver: order.address.receiver,
        phone: order.address.phone,
        address: order.address.address
      });
    }
    setModifyingOrderId(orderId);
    setShowAddressPopup(true);
  };

  const handleAddressSubmit = async () => {
    Toast.show({
      content: '收货地址修改成功',
      position: 'center'
    });
    setShowAddressPopup(false);
    if (refreshData) refreshData();
  };

  const handleReviewSubmit = async () => {
    Toast.show({
      content: '评价成功，感谢您的反馈！',
      position: 'center'
    });
    setShowReviewPopup(false);
    if (refreshData) refreshData();
  };

  const handleRefundSubmit = async () => {
    Toast.show({
      content: '退款申请已提交',
      position: 'center'
    });
    setShowRefundPopup(false);
    if (refreshData) refreshData();
  };

  return (
    <>
      <List header={`${status === 'all' ? '全部' : status}订单(${data.length})`}>
        {data.map(item => (
          <List.Item key={item.id}>
            <Card
              title={<span className={styles['order-card-title']}>{item.title}</span>}
              extra={<span className={styles['order-card-price']}>¥{item.price.toLocaleString()}</span>}
              className={styles['order-card']}
            >
              <div className={styles['order-info']}>
                <div className={styles['order-info-item']}>
                  <span className={styles['order-info-label']}>订单号:</span>
                  <span className={styles['order-info-value']}>{item.id}</span>
                </div>
                <div className={styles['order-info-item']}>
                  <span className={styles['order-info-label']}>下单时间:</span>
                  <span className={styles['order-info-value']}>
                    {new Date(item.time).toLocaleString()}
                  </span>
                </div>
                <div className={styles['order-info-item']}>
                  <span className={styles['order-info-label']}>状态:</span>
                  <span className={styles['order-card-status']}>{item.status}</span>
                </div>
                {item.refundReason && (
                  <div className={styles['order-info-item']}>
                    <span className={styles['order-info-label']}>退款原因:</span>
                    <span className={styles['order-info-value']}>{item.refundReason}</span>
                  </div>
                )}
              </div>

              {status === 'unpaid' && (
                <div>
                  <PaymentCountdown paymentTime={item.paymentTime} />
                  <div className={styles['button-container']}>
                    <Button className={styles['secondary-button']} onClick={() => handleCancelOrderClick(item.id)}>取消订单</Button>
                    <Button className={styles['primary-button']} onClick={() => handlePaymentClick(item.id)}>立即支付</Button>
                  </div>
                </div>
              )}

              {status === 'unsent' && (
                <div>
                  <div className={styles['button-container']}>
                    <Button className={styles['secondary-button']} onClick={() => handleModifyAddressClick(item.id)}>修改地址</Button>
                    <Button className={styles['secondary-button']} onClick={() => handleApplyRefundClick(item.id)}>申请退款</Button>
                    <Button className={styles['primary-button']} onClick={() => handleUrgeShipmentClick(item.id)}>催发货</Button>
                  </div>
                </div>
              )}

              {status === 'unreceived' && (
                <div>
                  <div className={styles['button-container']}>
                    <Button className={styles['secondary-button']} onClick={() => handleViewLogisticsClick(item.id)}>查看物流</Button>
                    <Button className={styles['secondary-button']} onClick={() => handleApplyRefundClick(item.id)}>申请退款</Button>
                    <Button className={styles['primary-button']} onClick={() => handleConfirmReceiptClick(item.id)}>确认收货</Button>
                  </div>
                </div>
              )}

              {status === 'uncommented' && (
                <div>
                  <div className={styles['button-container']}>
                    <Button className={styles['secondary-button']} onClick={() => handleAfterSaleClick(item.id)}>申请售后</Button>
                    <Button className={styles['secondary-button']} onClick={() => handleOrderAgainClick(item.id)}>再来一单</Button>
                    <Button className={styles['primary-button']} onClick={() => handleReviewClick(item.id)}>立即评价</Button>
                  </div>
                </div>
              )}

              {status === 'afterSales' && (
                <div>
                  <div className={styles['button-container']}>
                    <Button className={styles['secondary-button']} onClick={() => handleContactServiceClick(item.id)}>联系客服</Button>
                    <Button className={styles['primary-button']} onClick={() => handleViewRefundDetailClick(item.id)}>查看详情</Button>
                  </div>
                </div>
              )}
            </Card>
          </List.Item>
        ))}
        
        {/* InfiniteScroll for all orders */}
        {status === 'all' && (
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        )}
        
        {/* Cancel Order Popup */}
        <Popup
          visible={showPopup}
          onClose={() => setShowPopup(false)}
          bodyStyle={{ height: '40vh' }}
          position="bottom"
        >
          <div className={styles['popup-content']}>
            <h3>取消订单</h3>
            <Radio.Group onChange={value => setCancelReason(value)} value={cancelReason}>
              <Space direction='vertical'>
                <Radio value="不需要商品">暂时不需要这个商品</Radio>
                <Radio value="地址错误">收货地址选择/填写有误</Radio>
                <Radio value="规格错误">商品规格/款式/数量错选</Radio>
                <Radio value="价格问题">价格有点贵</Radio>
              </Space>
            </Radio.Group>
            <div className={styles['drawer-actions']}>
              <Button onClick={() => setShowPopup(false)}>我再想想</Button>
              <Button 
                color='primary' 
                onClick={() => handleCancelOrderConfirm(currentOrderId, cancelReason)}
                disabled={!cancelReason}
              >
                确认取消
              </Button>
            </div>
          </div>
        </Popup>
        
        {/* Review Popup */}
        <Popup
          visible={showReviewPopup}
          onClose={() => setShowReviewPopup(false)}
          bodyStyle={{ height: '60vh', padding: '20px' }}
          position="bottom"
        >
          <div className={styles['popup-content']}>
            <h3>商品评价</h3>
            <div style={{ margin: '15px 0' }}>
              <p>请对商品进行评分:</p>
              <Rate 
                value={rating} 
                onChange={setRating} 
                style={{ '--star-size': '32px', margin: '10px 0' }} 
              />
            </div>
            <div style={{ margin: '15px 0' }}>
              <p>评价内容:</p>
              <TextArea 
                placeholder="请输入您的评价内容" 
                value={comment}
                onChange={setComment}
                rows={5}
                style={{ '--font-size': '14px' }}
              />
            </div>
            <div className={styles['drawer-actions']}>
              <Button onClick={() => setShowReviewPopup(false)}>取消</Button>
              <Button 
                color='primary' 
                onClick={handleReviewSubmit}
                disabled={!comment}
              >
                提交评价
              </Button>
            </div>
          </div>
        </Popup>
        
        {/* Refund Popup */}
        <Popup
          visible={showRefundPopup}
          onClose={() => setShowRefundPopup(false)}
          bodyStyle={{ height: '60vh', padding: '20px' }}
          position="bottom"
        >
          <div className={styles['popup-content']}>
            <h3>申请退款</h3>
            <div style={{ margin: '15px 0' }}>
              <p>请选择退款原因:</p>
              <Radio.Group 
                value={refundReason} 
                onChange={setRefundReason}
              >
                <Space direction='vertical'>
                  <Radio value="商品质量问题">商品质量问题</Radio>
                  <Radio value="商品不符合描述">商品不符合描述</Radio>
                  <Radio value="发错货">发错货</Radio>
                  <Radio value="个人原因">个人原因</Radio>
                </Space>
              </Radio.Group>
            </div>
            <div style={{ margin: '15px 0' }}>
              <p>退款说明:</p>
              <TextArea 
                placeholder="请详细描述退款原因" 
                value={refundDescription}
                onChange={setRefundDescription}
                rows={5}
                style={{ '--font-size': '14px' }}
              />
            </div>
            <div className={styles['drawer-actions']}>
              <Button onClick={() => setShowRefundPopup(false)}>取消</Button>
              <Button 
                color='primary' 
                onClick={handleRefundSubmit}
                disabled={!refundDescription}
              >
                提交申请
              </Button>
            </div>
          </div>
        </Popup>
        
        {/* Address Popup */}
        <Popup
          visible={showAddressPopup}
          onClose={() => setShowAddressPopup(false)}
          bodyStyle={{ height: '60vh', padding: '20px' }}
          position="bottom"
        >
          <div className={styles['popup-content']}>
            <h3>修改收货地址</h3>
            <Form>
              <Form.Item label="收货人">
                <Input 
                  placeholder="请输入收货人姓名" 
                  value={addressForm.receiver}
                  onChange={val => setAddressForm({...addressForm, receiver: val})}
                />
              </Form.Item>
              <Form.Item label="联系电话">
                <Input 
                  placeholder="请输入联系电话" 
                  value={addressForm.phone}
                  onChange={val => setAddressForm({...addressForm, phone: val})}
                />
              </Form.Item>
              <Form.Item label="详细地址">
                <TextArea 
                  placeholder="请输入详细地址" 
                  rows={3}
                  value={addressForm.address}
                  onChange={val => setAddressForm({...addressForm, address: val})}
                />
              </Form.Item>
            </Form>
            <div className={styles['drawer-actions']}>
              <Button onClick={() => setShowAddressPopup(false)}>取消</Button>
              <Button 
                color='primary' 
                onClick={handleAddressSubmit}
                disabled={!addressForm.receiver || !addressForm.phone || !addressForm.address}
              >
                保存地址
              </Button>
            </div>
          </div>
        </Popup>
      </List>
    </>
  );
};

const PaymentCountdown = ({ paymentTime }) => {
  const [timeLeft, setTimeLeft] = useState(paymentTime);

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prevTime) => {
        if (prevTime <= 0) {
          clearInterval(timer);
          return 0;
        }
        return prevTime - 1000;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [paymentTime]);

  const minutes = Math.floor(timeLeft / 60000);
  const seconds = Math.floor((timeLeft % 60000) / 1000);
  const formattedTime = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;

  return (
    <div className={styles['countdown']}>
      支付倒计时：{formattedTime}
      {timeLeft <= 0 && <span style={{ color: 'red' }}> (已超时)</span>}
    </div>
  );
};

// 支付订单
const handlePayment = async (orderId, refreshData) => {
  try {
    Toast.show({
      content: '正在前往支付页面...',
      position: 'center'
    });
    
    // 模拟支付成功
    setTimeout(() => {
      Toast.show({
        content: '支付成功！',
        position: 'center'
      });
      if (refreshData) refreshData();
    }, 1500);
  } catch (error) {
    Toast.show({
      content: '支付过程中出现错误',
      position: 'center'
    });
  }
};

// 取消订单
const handleCancelOrder = async (orderId, reason, refreshData) => {
  try {
    Toast.show({
      content: `订单已取消，原因: ${reason || '未指定'}`,
      position: 'center'
    });
    if (refreshData) refreshData();
  } catch (error) {
    Toast.show({
      content: '取消订单失败',
      position: 'center'
    });
  }
};

// 催发货
const handleUrgeShipment = async (orderId) => {
  Toast.show({
    content: '已通知商家尽快发货',
    position: 'center'
  });
};

// 查看物流
const handleViewLogistics = async (orderId) => {
  const logisticsData = {
    carrier: '顺丰速运',
    trackingNumber: 'SF123456789',
    status: '运输中',
    logistics: [
      { time: '2023-10-01 10:00:00', content: '已发货', location: '深圳' },
      { time: '2023-10-02 15:30:00', content: '运输中', location: '广州转运中心' },
      { time: '2023-10-03 09:15:00', content: '运输中', location: '北京转运中心' }
    ]
  };
  
  let logisticsContent = `
    <div style="padding: 10px">
      <h3 style="text-align: center; margin-bottom: 15px">物流信息</h3>
      <p>物流公司: ${logisticsData.carrier || '未知'}</p>
      <p>运单号: ${logisticsData.trackingNumber || '未知'}</p>
      <p>物流状态: ${logisticsData.status || '未知'}</p>
      <hr />
      <div style="max-height: 300px; overflow-y: auto">
  `;
  
  logisticsData.logistics.forEach(item => {
    logisticsContent += `
      <div style="margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee">
        <p style="color: #666">${item.time}</p>
        <p style="font-weight: bold">${item.content}</p>
        <p style="color: #999">${item.location || ''}</p>
      </div>
    `;
  });
  
  logisticsContent += '</div></div>';
  
  Dialog.show({
    content: logisticsContent,
    closeOnAction: true,
    actions: [
      { key: 'close', text: '关闭' }
    ]
  });
};

// 确认收货
const handleConfirmReceipt = async (orderId, refreshData) => {
  Dialog.show({
    title: '确认收货',
    content: '请确认您已收到商品，且商品完好无损',
    closeOnAction: true,
    actions: [
      {
        key: 'cancel',
        text: '取消',
      },
      {
        key: 'confirm',
        text: '确认收货',
        bold: true,
        onClick: () => {
          Toast.show({
            content: '已确认收货，感谢您的购买！',
            position: 'center'
          });
          if (refreshData) refreshData();
        },
      },
    ]
  });
};

// 再来一单
const handleOrderAgain = (orderId) => {
  Toast.show({
    content: '已将商品加入购物车',
    position: 'center'
  });
};

// 申请售后
const handleAfterSale = (orderId) => {
  Dialog.show({
    title: '申请售后服务',
    content: (
      <div>
        <p>请选择服务类型:</p>
        <Radio.Group defaultValue="退货退款">
          <Space direction='vertical'>
            <Radio value="退货退款">退货退款</Radio>
            <Radio value="换货">换货</Radio>
            <Radio value="维修">维修</Radio>
            <Radio value="补发">补发</Radio>
          </Space>
        </Radio.Group>
        <p style={{ marginTop: '10px' }}>问题描述:</p>
        <TextArea placeholder="请详细描述您的问题" rows={3} />
      </div>
    ),
    closeOnAction: true,
    actions: [
      {
        key: 'cancel',
        text: '取消',
      },
      {
        key: 'confirm',
        text: '提交申请',
        bold: true,
        onClick: () => {
          Toast.show({
            content: '售后服务申请已提交',
            position: 'center'
          });
        },
      },
    ]
  });
};

// 联系客服
const handleContactService = (orderId) => {
    
  Dialog.show({
    title: '联系客服',
    content: (
      <div>
        <p>请选择联系方式:</p>
        <div style={{ margin: '10px 0' }}>
          <a href="http://localhost:5173/support">  
          <Button block color='primary' style={{ marginBottom: '10px' }} >
            
            在线客服
          </Button></a>
          <Button block color='primary'>
            电话客服: 400-123-4567
          </Button>
        </div>
      </div>
    ),
    closeOnAction: true,
    actions: [
      {
        key: 'close',
        text: '关闭',
      }
    ]
  });
};

// 查看退款详情
const handleViewRefundDetail = (orderId) => {
  const refundDetail = {
    orderId: orderId,
    status: '处理中',
    applyTime: '2023-10-01 14:30',
    reason: '商品质量问题',
    amount: 599,
    progress: [
      { time: '2023-10-01 14:30', status: '申请已提交' },
      { time: '2023-10-02 09:15', status: '商家处理中' }
    ]
  };
  
  let refundContent = `
    <div style="padding: 10px">
      <h3 style="text-align: center; margin-bottom: 15px">退款详情</h3>
      <div style="margin-bottom: 10px">
        <p><strong>订单号:</strong> ${refundDetail.orderId}</p>
        <p><strong>退款状态:</strong> ${refundDetail.status}</p>
        <p><strong>申请时间:</strong> ${refundDetail.applyTime}</p>
        <p><strong>退款原因:</strong> ${refundDetail.reason}</p>
        <p><strong>退款金额:</strong> ¥${refundDetail.amount}</p>
      </div>
      <hr />
      <h4 style="margin: 15px 0 10px">处理进度</h4>
      <div style="max-height: 300px; overflow-y: auto">
  `;
  
  refundDetail.progress.forEach(item => {
    refundContent += `
      <div style="margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee">
        <p style="font-weight: bold">${item.status}</p>
        <p style="color: #666">${item.time}</p>
      </div>
    `;
  });
  
  refundContent += '</div></div>';
  
  Dialog.show({
    content: refundContent,
    closeOnAction: true,
    actions: [
      { key: 'close', text: '关闭' }
    ]
  });
};

export default Operation;